package com.insthub.BeeFramework.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import com.insthub.BeeFramework.model.ActivityManagerModel;
import com.insthub.BeeFramework.model.BusinessMessage;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.photo.AlbumsActivity;

@SuppressLint("NewApi")
public class BaseActivity extends Activity implements Handler.Callback {
	public Handler mHandler;
	public static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
	public static final int PHOTO_REQUEST_GALLERY = 2;// 从相册选择
	public static final int PHOTO_REQUEST_CUT = 3;// 结果

	/* 头像名称 temp_photo.jpg*/
	public static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	public File tempFile;

	public BaseActivity() {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		mHandler = new Handler(this);
		ActivityManagerModel.addLiveActivity(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		ActivityManagerModel.addVisibleActivity(this);
	}

	@Override
	protected void onStop() {
		super.onStop();

		ActivityManagerModel.removeVisibleActivity(this);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();

		ActivityManagerModel.addForegroundActivity(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		ActivityManagerModel.removeForegroundActivity(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ActivityManagerModel.removeLiveActivity(this);
	}

	@Override
	public boolean handleMessage(Message msg) {
		return false;
	}

	public void OnMessageResponse(BusinessMessage response)
			throws JSONException {
		if (response.messageState == BusinessMessage.FAILURE_MESSAGE) {
		}
	}

	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	public void startActivityForResult(Intent intent, int requestCode) {
		super.startActivityForResult(intent, requestCode);
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	/**
	 * 将 2009-7-24 14:28:12 转换为对应的 2009-07-24
	 * 
	 * @param time
	 * @return date
	 */
	public static String getDateShort(String time) {
		String date = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d = sdf1.parse(time);
			date = sdf.format(d);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;

	}

	/**
	 * 将 2009-7-24 14:28:12 转换为对应的 14:28
	 * 
	 * @param time
	 * @return date
	 */
	public static String getTimeShort(String time) {
		String date = "";
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		try {
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d = sdf1.parse(time);
			date = sdf.format(d);

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;

	}

	/**
	 * 
	 * @param imgPath
	 * @param bitmap
	 * @param imgFormat
	 * 图片格式
	 * @return
	 */
	public String imgToBase64(String imgPath, Bitmap bitmap, String imgFormat) {
		if (imgPath != null && imgPath.length() > 0) {
			bitmap = readBitmap(imgPath);
		}
		if (bitmap == null) {
			// bitmap not found!!
		}
		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 40, out);

			out.flush();
			out.close();

			byte[] imgBytes = out.toByteArray();
			return Base64.encodeToString(imgBytes, Base64.DEFAULT);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private Bitmap readBitmap(String imgPath) {
		try {
			return BitmapFactory.decodeFile(imgPath);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return null;
		}

	}

	public void dialogNote() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("图片上传");
		builder.setItems(new String[] { "相机拍照", "本地选择" },
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:

							// 判断存储卡是否可以用，可用进行存储
							if (hasSdcard()) {
								Intent camera = new Intent(
										"android.media.action.IMAGE_CAPTURE");
								tempFile = new File(Environment
										.getExternalStorageDirectory(),
										PHOTO_FILE_NAME);
								// 从文件中创建uri
								Uri uri = Uri.fromFile(tempFile);
								camera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
								// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
								startActivityForResult(camera,
										PHOTO_REQUEST_CAREMA);
							} else {
								Toast.makeText(BaseActivity.this, "无SD卡",
										Toast.LENGTH_SHORT).show();
							}

							break;

						case 1:
							Intent intent = new Intent(BaseActivity.this,
									AlbumsActivity.class);
							startActivity(intent);
							break;
						}
					}
				});
		builder.create().show();
	}

	public boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 隐藏系统键盘
	 */
	public static void hideSystemKeyBoard(Context mcontext, View v) {
		InputMethodManager imm = (InputMethodManager) (mcontext)
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	public void dialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle("头像设置");
		builder.setItems(new String[] { "相机拍照", "相册选择" },
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							Intent camera = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							if (hasSdcard()) {
								tempFile = new File(Environment
										.getExternalStorageDirectory(),
										PHOTO_FILE_NAME);
								Uri uri = Uri.fromFile(tempFile);
								camera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
							}
							startActivityForResult(camera, PHOTO_REQUEST_CAREMA);
							break;

						case 1:
							Intent gallery = new Intent(Intent.ACTION_PICK);
							gallery.setType("image/*");
							startActivityForResult(gallery,
									PHOTO_REQUEST_GALLERY);
							break;
						}
					}
				});
		builder.create().show();
	}

	/*
	 * 剪切图片
	 */
	public void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

}
